package com.lun.swordtowardoffer2.c05;

public class IsAlienSorted {
	
	public boolean isAlienSorted(String[] words, String order) {
		int[] orderArray = new int[order.length()];
		for(int i = 0; i < orderArray.length; i++) {
			orderArray[order.charAt(i) - 'a'] = i;
		}
		
		for(int i = 0; i < words.length - 1; i++) {
			 if(!isSorted(words[i], words[i + 1], orderArray)) {
				 return false; 
			 }
		}
		
		return true;
	}
	
	private boolean isSorted(String word1, String word2, int[] orderArray) {
		int i = 0;
		for(; i < word1.length() && i < word2.length(); i++) {
			int diff = orderArray[word1.charAt(i) - 'a'] - orderArray[word2.charAt(i) - 'a'];
			if(diff == 0)
				continue;
			else
				return diff < 0;
		}
		return i == word1.length();//考虑"abc", "abcde"情况
	}
	
}
